package com.ctshk.rpc.certificate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.certificate.dto.AppointmentHkMacauCarDTO;
import com.ctshk.rpc.certificate.dto.CertificateAcceptDTO;
import com.ctshk.rpc.certificate.dto.CertificateHkMacauCarDTO;
import com.ctshk.rpc.certificate.entity.CertificateHkMacauCar;
import com.ctshk.rpc.certificate.mapper.CertificateBusinessMapper;
import com.ctshk.rpc.certificate.mapper.CertificateHkMacauCarMapper;
import com.ctshk.rpc.certificate.req.*;
import com.ctshk.rpc.certificate.service.ICertificateHkMacauCarService;
import com.ctshk.rpc.certificate.utils.OrderUtil;
import com.ctshk.rpc.system.service.IValidateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 港澳私人小汽车入出内地移位牌证业务 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-03-25
 */
@DubboService
public class CertificateHkMacauCarServiceImpl extends ServiceImpl<CertificateHkMacauCarMapper, CertificateHkMacauCar> implements ICertificateHkMacauCarService {

    @Autowired
    private CertificateHkMacauCarMapper hkMacauCarMapper;

    @Autowired
    private CertificateBusinessMapper businessMapper;

    @DubboReference
    private IValidateService validateService;
    
    @Override
    public Result saveHkMacauCar(CertificateHkMacauCarReq certificateHkMacauCarReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (certificateHkMacauCarReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        // 有id保存
        CertificateHkMacauCar certificateHkMacauCar;
        if (null != certificateHkMacauCarReq.getId()) {
            certificateHkMacauCar = hkMacauCarMapper.selectById(certificateHkMacauCarReq.getId());
            if (Objects.isNull(certificateHkMacauCar)) {
                return Result.failed(SystemError.SYS_411);
            }
            BeanUtils.copyProperties(certificateHkMacauCarReq, certificateHkMacauCar);
            certificateHkMacauCar.setModifiedId(userId);
            certificateHkMacauCar.setGmtModified(LocalDateTime.now());
            hkMacauCarMapper.updateById(certificateHkMacauCar);
        } else {
            // 保存预约单据
            certificateHkMacauCar = new CertificateHkMacauCar();
            BeanUtils.copyProperties(certificateHkMacauCarReq, certificateHkMacauCar);
            Long permitId = SnowflakeIdWorker.nextId();
            certificateHkMacauCar.setId(permitId);
            String registerNumber = OrderUtil.getReentryPermitRegisterNumber();
            certificateHkMacauCar.setRegisterNumber(registerNumber);
            certificateHkMacauCar.setCreateId(userId);
            certificateHkMacauCar.setGmtCreate(LocalDateTime.now());
            certificateHkMacauCar.setAcceptStatus(1);
            certificateHkMacauCar.setIsDeleted(0);
            hkMacauCarMapper.insert(certificateHkMacauCar);
        }

        // 预约办证中心
        if (certificateHkMacauCar.getSubmissionStatus() == 1) {
            Long res = businessMapper.reserveReentryPermit(certificateHkMacauCarReq.getName(), certificateHkMacauCarReq.getBusinessHallId(),
                    certificateHkMacauCarReq.getReserveDate(), certificateHkMacauCarReq.getReserveTime());
            if (res != 1) {
                return Result.failed(new BusinessException(SystemError.CERTIFICATE_BUSINESS_16002));
            }
        }
        
        return Result.success(certificateHkMacauCar.getId());
    }

    @Override
    public CertificateHkMacauCarDTO queryDetail(Long id) {
        CertificateHkMacauCar certificateHkMacauCar = hkMacauCarMapper.selectById(id);
        if (Objects.isNull(certificateHkMacauCar)) {
            throw new BusinessException(SystemError.SYS_411);
        }
        CertificateHkMacauCarDTO hkMacauCarDTO = new CertificateHkMacauCarDTO();
        BeanUtils.copyProperties(certificateHkMacauCar, hkMacauCarDTO);
        return hkMacauCarDTO;
    }

    @Override
    public Result updateHkMacauCar(CertificateHkMacauCarReq certificateHkMacauCarReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (certificateHkMacauCarReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        CertificateHkMacauCar certificateHkMacauCar = hkMacauCarMapper.selectById(certificateHkMacauCarReq.getId());
        if (Objects.isNull(certificateHkMacauCar)) {
            return Result.failed(SystemError.SYS_411);
        }
        BeanUtils.copyProperties(certificateHkMacauCarReq, certificateHkMacauCar);
        certificateHkMacauCar.setModifiedId(userId);
        certificateHkMacauCar.setGmtModified(LocalDateTime.now());
        hkMacauCarMapper.updateById(certificateHkMacauCar);
        return Result.success();
    }

    @Override
    public Result procReserveHkMacauCar(ProcCommonCertificateReq procReserveHkMacauCarReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (procReserveHkMacauCarReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        CertificateHkMacauCar certificateHkMacauCar = hkMacauCarMapper.selectById(procReserveHkMacauCarReq.getId());
        if (Objects.isNull(certificateHkMacauCar)) {
            return Result.failed(SystemError.SYS_411);
        }
        certificateHkMacauCar.setAcceptStatus(procReserveHkMacauCarReq.getAcceptStatus());
        certificateHkMacauCar.setModifiedId(userId);
        certificateHkMacauCar.setGmtModified(LocalDateTime.now());
        certificateHkMacauCar.setAcceptDesc(procReserveHkMacauCarReq.getAcceptDesc());
        hkMacauCarMapper.updateById(certificateHkMacauCar);
        return Result.success();
    }

    @Override
    public PageResponse<CertificateAcceptDTO> queryCertificateAcceptList(CertificateAcceptPageReq req) {
        Page<CertificateHkMacauCar> certificatePage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<CertificateHkMacauCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(null != req.getApplyTypeId(), CertificateHkMacauCar::getApplyTypeId, req.getApplyTypeId());
        queryWrapper.lambda().like(StringUtils.isNotBlank(req.getPhoneNum()), CertificateHkMacauCar::getPhoneNum, req.getPhoneNum());
        queryWrapper.lambda().like(StringUtils.isNotBlank(req.getEmail()), CertificateHkMacauCar::getEmail, req.getEmail());
        queryWrapper.lambda().eq(null != req.getAcceptStatus(), CertificateHkMacauCar::getAcceptStatus, req.getAcceptStatus());

        // 处理时间区间不包括右边界问题
        if (null != req.getGmtCreateEnd()) {
            req.setGmtCreateEnd(req.getGmtCreateEnd().plusDays(1));
        }
        queryWrapper.lambda().between((null != req.getGmtCreateBegin() && null != req.getGmtCreateEnd()), CertificateHkMacauCar::getGmtCreate,req.getGmtCreateBegin(),req.getGmtCreateEnd());
        Page<CertificateHkMacauCar> iPage = hkMacauCarMapper.selectPage(certificatePage, queryWrapper);
        List<CertificateHkMacauCar> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        List<CertificateAcceptDTO> certificateAcceptQueryDTOList = EntityUtil.copyList(records, CertificateAcceptDTO.class);
        certificateAcceptQueryDTOList.forEach(record -> record.setCnName("-"));
        return new PageResponse<>(certificateAcceptQueryDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public Result<AppointmentHkMacauCarDTO> queryAppointmentInfo(QueryHkMacauCarReq queryAppointmentInfoReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        validateService.check(queryAppointmentInfoReq.getKey(), queryAppointmentInfoReq.getCode());
        CertificateHkMacauCar hkMacauCar = hkMacauCarMapper.selectOne(new QueryWrapper<CertificateHkMacauCar>().lambda()
                .eq(null != queryAppointmentInfoReq.getId(), CertificateHkMacauCar::getId, queryAppointmentInfoReq.getId())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getCertificateNo()), CertificateHkMacauCar::getCertificateNo,queryAppointmentInfoReq.getCertificateNo())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getRegisterNumber()), CertificateHkMacauCar::getRegisterNumber,queryAppointmentInfoReq.getRegisterNumber())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getApprovalNumber()), CertificateHkMacauCar::getApprovalNumber,queryAppointmentInfoReq.getApprovalNumber())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getPlateNumber()), CertificateHkMacauCar::getRegisterNumber,queryAppointmentInfoReq.getPlateNumber()));

        AppointmentHkMacauCarDTO appointmentInfoDTO = new AppointmentHkMacauCarDTO();
        BeanUtils.copyProperties(hkMacauCar, appointmentInfoDTO);
        return Result.success(appointmentInfoDTO);
    }

    @Override
    public Result cancelAppointment(Long id, Long userId) {
        CertificateHkMacauCar hkMacauCar = hkMacauCarMapper.selectById(id);
        if (Objects.isNull(hkMacauCar)) {
            return Result.failed(SystemError.SYS_411);
        }
        hkMacauCar.setAcceptStatus(0);
        hkMacauCarMapper.updateById(hkMacauCar);
        return Result.success(hkMacauCar.getRegisterNumber());
    }
}
